package com.shiliuzi.www.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component
public class EmailUtil {

    @Value("${spring.mail.from}")
    private String fromEmail;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Resource
    private JavaMailSender javamailSender;

    @Transactional
    public boolean sendMessage (String toEmail, String title, Object content) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(fromEmail);
            simpleMailMessage.setTo(toEmail);
            simpleMailMessage.setSubject(title);
            simpleMailMessage.setSentDate(new Date());
            simpleMailMessage.setText("验证码为："+content+"，请在60s内进行登录!");
            javamailSender.send(simpleMailMessage);
            log.info("发送邮件成功：{}->{}",sendMailer,toEmail);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
